<?php

/**
 * This is the model class for table "ham_group".
 *
 * The followings are the available columns in table 'ham_group':
 * @property integer $id
 * @property string $name
 * @property string $description
 * @property string $created_at
 * @property integer $created_by
 *
 * The followings are the available model relations:
 * @property User $createdBy
 * @property GroupContact[] $groupContacts
 */
class Group extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Group the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'ham_group';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name', 'required', 'message' => Yii::t('main','Vui lòng nhập tên nhóm liên hệ')),
			array('name, description', 'length', 'max'=>255),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, description, created_at, created_by', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'createdBy' => array(self::BELONGS_TO, 'User', 'created_by'),
			'groupContacts' => array(self::HAS_MANY, 'GroupContact', 'group_id'),
		);
	}

	public function beforeSave(){
		if($this->isNewRecord){
			$this->created_at = date('Y-m-d H:i');
		}
		return parent::beforeSave();
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => Yii::t('main','Tên nhóm liên hệ'),
			'description' => Yii::t('main','Mô tả'),
			'created_at' => 'Created At',
			'created_by' => 'Created By',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('created_at',$this->created_at,true);
		$criteria->compare('created_by',$this->created_by);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Function to insert/update group
	 */
	public function updateGroup(){
		$result = array('msg' => '', 'success' => false);
		if($this->isNewRecord){
			$this->created_by = Yii::app()->user->getId();
			$result['success'] = $this->insert();
			$result['msg'] = Yii::t('main', 'Tạo mới thành công!');
		}else{
			$result['success'] = $this->update();
			$result['msg'] = Yii::t('main', 'Cập nhật thành công!');
		}
		return $result;
	}

	/**
	 * Function get value of col nam
	 */
	public function getColName(){
		$viewContactsLink = CHtml::link(Yii::t('main','[Xem DS]'), Yii::app()->createUrl('groups/contacts/manage/id/'.$this->id));
		return $this->name . ' <strong>('.$this->countContacts().')</strong>&nbsp;'.$viewContactsLink;
	}

	/**
	 * Function count contacts in group
	 */
	public function countContacts($id = null){
		if(!empty($id)){
			$model = GroupContact::model()->countByAttributes(array('group_id' => $id));
		}else{
			return count($this->groupContacts);
		}
	}


	/**
	 * Function to add contacts to group
	 */
	public function addToGroup($contacts = array()){
		$result = true;
		foreach($contacts as $c){
			$contact = Contact::model()->countByAttributes(array('id' => $c));
			if($contact != 1) continue;
			$groupContact = GroupContact::model()->countByAttributes(array('group_id' => $this->id, 'contact_id' => $c));
			if($groupContact > 0) continue;
			$groupContact = new GroupContact();
			$groupContact->group_id = $this->id;
			$groupContact->contact_id = $c;
			$groupContact->insert();
		}
		return $result;
	}

	// Delete group
	public function deleteGroup(){
		$transaction= $this->dbConnection->beginTransaction();
		$result = true;
		try{
			foreach($this->groupContacts as $gc){
				if(!$gc->delete()){
					$result = false;
					break;
				}
			}
		    if($result === true){
		    	$result = $this->delete();
		    }

		    if($result === true){
		        $transaction->commit();
		    }else{
		        $transaction->rollback();
		    }
		    return $result;
		}
		catch(Exception $e)
		{
		    $transaction->rollback();
		    return false;
		}
	}
	
}